package com.gaga.console.base.utils;

import com.gaga.console.base.config.JavaFxConfig;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

public class VideoPlayerUtils {

    private static Stage videoStage;
    private static BorderPane borderPane;
    private static MediaPlayer mediaPlayer;

    private static final double WINDOW_DECORATION_WIDTH = 14;  // 边框+滚动条
    private static final double WINDOW_DECORATION_HEIGHT = 85; // 标题栏+菜单栏

    // 私有构造方法防止实例化
    private VideoPlayerUtils() {
    }


    public static void createWindow(double width, double height, String title, String backgroundColor, File iconFile) {
        JavaFxConfig.runSafe(() -> {
            if (videoStage == null) {
                initializeNewWindow(width, height, title, backgroundColor, iconFile);
            } else {
                handleExistingWindow(width, height, title, backgroundColor, iconFile);
            }
        });
    }

    private static void initializeNewWindow(double width, double height, String title, String color, File iconFile) {
        videoStage = new Stage();
        borderPane = new BorderPane();

        if (iconFile != null) {
            // 设置窗口图标
            setWindowIcon(iconFile);
        }

        // 设置窗口关闭事件监听
        videoStage.setOnCloseRequest(e -> {
            cleanUpResources();
            videoStage = null;  // 重要：解除实例引用
        });

        applyWindowSettings(width, height, title, color);
        videoStage.setScene(new Scene(borderPane, width, height));
        videoStage.show();
    }

    private static void handleExistingWindow(double width, double height, String title, String color, File iconFile) {
        // 窗口已关闭但引用未清理时的保护逻辑
        if (!videoStage.isShowing()) {
            cleanUpResources();
            initializeNewWindow(width, height, title, color, iconFile);
            return;
        }
        
        // 仅更新标题和背景色，保留当前窗口大小
        if (StringUtils.isNotBlank(title)) {
            videoStage.setTitle(title);
        }
        
        if (StringUtils.isNotBlank(color)) {
            borderPane.setStyle("-fx-background-color: " + color + ";");
        }
        
        // 更新图标（如果提供）
        if (iconFile != null) {
            setWindowIcon(iconFile);
        }
    }

    private static void setWindowIcon(File iconFile) {
        String iconPath = "";
        try {
            // 清除旧图标
            videoStage.getIcons().clear();
            // 加载新图标（支持多尺寸）
            Image appIcon = new Image(iconFile.toURI().toString());
            videoStage.getIcons().add(appIcon);
        } catch (Exception e) {
            System.err.println("图标加载失败: " + e.getMessage());
        }
    }


    private static void applyWindowSettings(double width, double height, String title, String color) {
        // 设置样式和布局参数
        if (StringUtils.isNotBlank(color)) {
            borderPane.setStyle("-fx-background-color: " + color + ";");
        }
        borderPane.setPrefSize(width, height);

        // 配置窗口属性
        videoStage.setTitle(title);
        videoStage.setWidth(width + 16);  // 补偿窗口边框
        videoStage.setHeight(height + 39); // 补偿标题栏
    }

    /**
     * @deprecated 此方法已不再使用，保留仅供参考
     */
    @Deprecated
    private static void updateWindowSettings(double width, double height, String title, String color) {
        // 更新样式和布局
        if (StringUtils.isNotBlank(color)) {
            borderPane.setStyle("-fx-background-color: " + color + ";");
        }
        borderPane.setPrefSize(width, height);

        // 更新窗口属性
        videoStage.setTitle(title);
        videoStage.setWidth(width + WINDOW_DECORATION_WIDTH);
        videoStage.setHeight(height + WINDOW_DECORATION_HEIGHT);
    }

    public static void playVideo(String videoPath) {
        JavaFxConfig.runSafe(() -> {
            validateWindowState();
            initializeMediaPlayer(videoPath);

            // 设置媒体加载完成监听器
            mediaPlayer.setOnReady(() -> {
                MediaView mediaView = new MediaView(mediaPlayer);
                configureVideoScaling(mediaView);
                borderPane.setCenter(mediaView);
                mediaPlayer.play();
            });
        });
    }

    // 核心修改部分
    private static void configureVideoScaling(MediaView mediaView) {
        Media media = mediaView.getMediaPlayer().getMedia();
        double videoWidth = media.getWidth();
        double videoHeight = media.getHeight();
        double aspectRatio = videoWidth / videoHeight;

        // 关键缩放配置 - 保持视频比例
        mediaView.setPreserveRatio(true);
        mediaView.setSmooth(true);

        // 动态绑定媒体视图尺寸，但不改变窗口大小
        borderPane.widthProperty().addListener((obs, oldVal, newWidth) -> {
            double contentWidth = newWidth.doubleValue();
            double targetHeight = contentWidth / aspectRatio;
            try {
                mediaView.setFitWidth(contentWidth);
                mediaView.setFitHeight(targetHeight);
            } catch (Exception e) {
                // 忽略异常
            }
        });

        borderPane.heightProperty().addListener((obs, oldVal, newHeight) -> {
            double contentHeight = newHeight.doubleValue();
            double targetWidth = contentHeight * aspectRatio;
            try {
                mediaView.setFitHeight(contentHeight);
                mediaView.setFitWidth(targetWidth);
            } catch (Exception e) {
                // 忽略异常
            }
        });

        // 初始设置 - 使视频充满当前BorderPane
        mediaView.fitWidthProperty().bind(borderPane.widthProperty());
        mediaView.fitHeightProperty().bind(borderPane.heightProperty());
    }

    private static void validateWindowState() {
        if (videoStage == null || borderPane == null) {
            throw new IllegalStateException("请先调用 createWindow 初始化播放窗口");
        }
    }

    private static void initializeMediaPlayer(String videoPath) {
        cleanUpMediaPlayer(); // 清理之前的播放器
        try {
            Media media = new Media(new File(videoPath).toURI().toString());
            mediaPlayer = new MediaPlayer(media);
            mediaPlayer.setCycleCount(1);
            mediaPlayer.setVolume(0);
        } catch (Exception e) {
            throw new RuntimeException("媒体初始化失败: " + e.getMessage());
        }
    }

    public static void cleanUpMediaPlayer() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.dispose();
            mediaPlayer = null;
            borderPane.setCenter(null);
        }
    }

    public static void closeWindow() {
        JavaFxConfig.runSafe(() -> {
            cleanUpResources();
            if (videoStage != null) {
                videoStage.close();
                videoStage = null;
            }
        });
    }

    private static void cleanUpResources() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.dispose();
            mediaPlayer = null;
        }
        if (borderPane != null) {
            borderPane.setCenter(null);
            borderPane = null;
        }
    }

    /**
     * @deprecated 此方法已不再使用，保留仅供参考
     */
    @Deprecated
    private static double[] calculateWindowDecoration(Stage stage) {
        Scene scene = stage.getScene();
        double contentWidth = scene.getWidth();
        double contentHeight = scene.getHeight();
        double totalWidth = stage.getWidth();
        double totalHeight = stage.getHeight();

        return new double[]{
                totalWidth - contentWidth, // 宽度装饰
                totalHeight - contentHeight // 高度装饰
        };
    }
}